package org.SMSReceiver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class MySMS extends Activity {

	// ---Name space reference for Intent extras---
	public static final String message = "org.SMSReceiver.message";
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;
	private TextView timeDisplay;
	private TextView dateDisplay;
	private AutoCompleteTextView eventView;
	private AutoCompleteTextView placeView;
	private AutoCompleteTextView descriptionView;
	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// ---Initialize the Activity and set view---
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_alt);

		// ---Assign the views---
		// ---Text Boxes for Date and Time---
		dateDisplay = (TextView) findViewById(R.id.autocomplete_date);
		timeDisplay = (TextView) findViewById(R.id.autocomplete_time);

		Button pickDate = (Button) findViewById(R.id.pickDate);
		Button pickTime = (Button) findViewById(R.id.pickTime);

		Button save = (Button) findViewById(R.id.save);
		Button goToCalendar = (Button) findViewById(R.id.goToCalendar);
		// ---add a click listener to the "set date" button---
		pickDate.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		// ---add a click listener to the "set time" button---
		pickTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		// ---add a click listener to the "save" button---
		save.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO FOR Daler
				if (TextUtils.isEmpty(dateDisplay.getText())) {
					Toast.makeText(MySMS.this, "Please enter date.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(timeDisplay.getText())) {
					Toast.makeText(MySMS.this, "Please enter time.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(eventView.getText())) {
					Toast.makeText(MySMS.this, "Please enter event name.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(placeView.getText())) {
					Toast.makeText(MySMS.this, "Please enter place name.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(descriptionView.getText())) {
					Toast.makeText(MySMS.this, "Please enter description.",
							Toast.LENGTH_SHORT).show();
					return;
				}

				dateDisplay.setEnabled(false);
				timeDisplay.setEnabled(false);
				eventView.setEnabled(false);
				placeView.setEnabled(false);
				descriptionView.setEnabled(false);

				// ---Strings that need to be saved---\
				String date = dateDisplay.getText().toString();
				String time = timeDisplay.getText().toString();
				String event = eventView.getText().toString();
				String place = placeView.getText().toString();
				String description = descriptionView.getText().toString();
				Toast.makeText(MySMS.this,
						event + " " + place + " " + description + " ",
						Toast.LENGTH_LONG).show();

				try {
					File root = Environment.getExternalStorageDirectory();
					File xfile = new File(root, "data.txt");
					FileWriter writer = new FileWriter(xfile);

					writer.append("Date: " + date);
					writer.append("Time: " + time);
					writer.append("Event: " + event);
					writer.append("Place: " + place);
					writer.append("Description" + description);
					writer.flush();
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}

				try {
					File root = Environment.getExternalStorageDirectory();
					File xfile = new File(root, "data.txt");
					FileReader reader = new FileReader(xfile);
					String sCurrentLine;

					BufferedReader br = new BufferedReader(reader);
					while ((sCurrentLine = br.readLine()) != null) {
						System.out.println(sCurrentLine+"\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});

		// ---add a click listener to the "Go To Calendar" button---
		goToCalendar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (TextUtils.isEmpty(eventView.getText())) {
					Toast.makeText(MySMS.this, "Please enter event name.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(placeView.getText())) {
					Toast.makeText(MySMS.this, "Please enter place name.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (TextUtils.isEmpty(descriptionView.getText())) {
					Toast.makeText(MySMS.this, "Please enter description.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				// ---Strings that need to be inserted to Calendar---
				/**
				 * TO JeeYoung START HERE:
				 */
			}
		});

		// ---get the current date---
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);

		// ---display the current date---
		updateDisplay();

		// ---Retrieve message text from Intent Extras---
		String messageText = null;
		messageText = getIntent().getExtras().getString(message);

		// ---Make a text box for displaying SMS message---
		TextView smsDisplay;
		smsDisplay = (TextView) findViewById(R.id.smsDisplay);
		smsDisplay.setText(messageText);

		// ---Store the message text tokens into String array---
		String[] words = Tokenize(messageText);

		// ---Make an AutoComplete TextView object---
		makeAutoComplete(words);
	}

	/**
	 * Creates AutoCompleteTextView object. Layout is defined in res/layout
	 * folder.
	 * 
	 * @param array
	 */
	public void makeAutoComplete(String[] array) {
		eventView = (AutoCompleteTextView) findViewById(R.id.autocomplete_event);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.list_item, array);
		eventView.setAdapter(adapter);

		placeView = (AutoCompleteTextView) findViewById(R.id.autocomplete_place);
		placeView.setAdapter(adapter);

		descriptionView = (AutoCompleteTextView) findViewById(R.id.autocomplete_description);
		descriptionView.setAdapter(adapter);
	}

	/**
	 * Converts given text into tokens using delimiters. Stores the tokens in
	 * String array and returns the array.
	 * 
	 * @param text
	 * @return
	 */
	public String[] Tokenize(String text) {
		final String DELiMITER_CHARS = " !?.;-)(*^%#!~";

		ArrayList<String> WList = new ArrayList<String>();

		StringTokenizer tok = new StringTokenizer(text, DELiMITER_CHARS);
		while (tok.hasMoreTokens()) {
			WList.add(tok.nextToken());
		}

		String[] WORDS = new String[WList.size()];
		WORDS = (String[]) WList.toArray(WORDS);

		return WORDS;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case TIME_DIALOG_ID:
			((TimePickerDialog) dialog).updateTime(mHour, mMinute);
			break;
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	/**
	 * Updates the date in the TextView
	 */
	private void updateDisplay() {
		dateDisplay.setText(new StringBuilder()
				// ---Month is 0 based so add 1---
				.append(mMonth + 1).append("-").append(mDay).append("-")
				.append(mYear));
		timeDisplay.setText(new StringBuilder().append(pad(mHour)).append(":")
				.append(pad(mMinute)));

	}

	/**
	 * the callback received when the user "sets" the date in the dialog
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	/**
	 * the callback received when the user "sets" the time in the dialog
	 */
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplay();
		}
	};

	/**
	 * @param c
	 *            : hour,minute
	 * @return the appropriate string representation of the hour or minute- it
	 *         will prefix a zero to the number if it's a single digit
	 */
	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}
}
